package com.learn.mybatis.typehandler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.learn.mybatis.bean.EmpStatus;
import org.apache.ibatis.type.*;

/**
 * 实现TypeHandler接口。或者继承BaseTypeHandler
 */
@MappedJdbcTypes(JdbcType.VARCHAR)
@MappedTypes(com.learn.mybatis.bean.EmpStatus.class)
public class MyEnumEmpStatusTypeHandler extends BaseTypeHandler<EmpStatus> {


    /**
     * 定义当前数据如何保存到数据库中的setParameter方法，调用的为空时的判断
     * 调用原生JDBC，给SQL传参
     */

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, EmpStatus parameter, JdbcType jdbcType) throws SQLException {
        System.out.println("setNonNullParameter--要保存的状态码数据为：" + String.valueOf(EmpStatus.getEmpStatusByCode(Integer.valueOf(i)).getCode()));
        ps.setString(i,String.valueOf(EmpStatus.getEmpStatusByCode(Integer.valueOf(i)).getCode()));
    }

    /**
     * 从返回结果中，按照列名封装bean
     * @return
     */
    @Override
    public EmpStatus getNullableResult(ResultSet rs, String columnName) throws SQLException {
        int code = rs.getInt(columnName);
        System.out.println("getNullableResult(ResultSet rs, String columnName)--从数据库中获取的状态码：" + code);
        EmpStatus status = EmpStatus.getEmpStatusByCode(code);
        return status;

    }

    /**
     * 从返回的结果中，按照列的索引，封装bean
     * @return
     */
    @Override
    public EmpStatus getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        int code = rs.getInt(columnIndex);
        System.out.println("getNullableResult(ResultSet rs, int columnIndex)--从数据库中获取的状态码：" + code);
        EmpStatus status = EmpStatus.getEmpStatusByCode(code);
        return status;
    }

    /**
     * 从存储过程中，按照列的索引，封装bean
     * @return
     */
    @Override
    public EmpStatus getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        int code = cs.getInt(columnIndex);
        System.out.println("getNullableResult(CallableStatement cs, int columnIndex)--从数据库中获取的状态码：" + code);
        EmpStatus status = EmpStatus.getEmpStatusByCode(code);
        return status;
    }
}
